package com.wuhao.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuhao.springboot.entity.*;
import com.wuhao.springboot.entity.dto.OrderPageDTO;
import com.wuhao.springboot.entity.ro.*;
import com.wuhao.springboot.entity.vo.OrderPageVO;
import com.wuhao.springboot.mapper.OrderMapper;
import com.wuhao.springboot.mapper.RepairTaskMapper;
import com.wuhao.springboot.service.IUserService;
import com.wuhao.springboot.service.OrderService;
import com.wuhao.springboot.type.StatusEnum;
import com.wuhao.springboot.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @Description
 * @Date 2023/1/31 8:01
 * @Author pq
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private RepairTaskMapper repairTaskMapper;

    @Resource
    private RepairTaskServiceImpl repairTaskServiceImpl;

    @Resource
    private IUserService userService;


    @Override
    public void addOrder(FaultDetection ro) {
        FaultDetection faultDetection;
        try {
            User currentUser = TokenUtils.getCurrentUser();
            Order order = new Order();
            order.setSubmitTime(new Date());
            order.setAirCondCode(ro.getAirCondCode());
            order.setAirCondType(ro.getAirCondType());
            order.setSpeculateReason(ro.getSpeculateReason());
            order.setRepairReco(ro.getRepairReco());
            assert currentUser != null;
            order.setUserId(currentUser.getId());
            order.setStatus(StatusEnum.TOBE_APPOINT);
            this.save(order);
        } catch (Exception e) {
            System.out.println("维修订单创建失败");
            throw new RuntimeException(e);
        }
    }

    @Override
    public OrderPageVO page(OrderPageRO ro) {
        QueryWrapper<Order> qw = new QueryWrapper<>();
        Page<Order> orderPage = new Page<>(ro.getCurrent(), ro.getSize());
        IPage<Order> orderIPage = orderMapper.selectPage(orderPage, qw);
        List<OrderPageDTO> orderPageDTOS = Lists.newArrayList();

        orderIPage.getRecords().forEach(order -> {
            OrderPageDTO dto = new OrderPageDTO();
            User user = userService.getById(order.getUserId());
            dto.setApplyUser(user.getUsername());
            dto.setType(order.getAirCondType());
            dto.setReason(order.getSpeculateReason());
            dto.setStatus(order.getStatus().getDesc());
            if (order.getScore() == 0) {
                dto.setScore("-");
            } else {
                dto.setScore(String.valueOf(order.getScore()));
            }
            dto.setId(order.getId());
            if (Objects.nonNull(order.getAppointTime())) {
                dto.setAppointTime(order.getAppointTime());
            }
            if (Objects.nonNull(order.getSubmitTime())) {
                dto.setSubmitTime(order.getSubmitTime());
            }
            User repairer = userService.getById(order.getRepairerId());
            if (Objects.nonNull(repairer)) {
                dto.setRepairer(repairer.getUsername());
            } else {
                dto.setRepairer("-");
            }
            orderPageDTOS.add(dto);
        });
        OrderPageVO vo = new OrderPageVO();
        vo.setRecords(orderPageDTOS);
        vo.setTotal(orderIPage.getTotal());
        vo.setPages(orderIPage.getPages());
        return vo;
    }

    @Override
    public void edit(EditRO ro) {
        Order order = orderMapper.selectById(ro.getId());
        try {
            BeanUtils.copyProperties(order, ro);
            orderMapper.updateById(order);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(EditRO ro) {
        RepairTask repairTask=repairTaskMapper.selectById(ro.getId());
        repairTaskMapper.deleteById(repairTask);
        orderMapper.deleteById(ro.getId());
    }

    @Override
    public void appoint(AppointRO ro) {
        Order order = orderMapper.selectById(ro.getId());
        order.setAppointTime(ro.getAppointTime());
        order.setStatus(StatusEnum.TOBE_REPAIR);
        orderMapper.updateById(order);
    }

    @Override
    public void score(ScoreRO ro) {
        Order order = orderMapper.selectById(ro.getId());
        order.setScore(Integer.parseInt(ro.getScore()));
        order.setStatus(StatusEnum.SCORED);

        QueryWrapper<RepairTask> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_id",ro.getId());

        RepairTask repairTask = repairTaskMapper.selectOne(queryWrapper);
        repairTask.setScore(ro.getScore());
        repairTaskMapper.updateById(repairTask);
        orderMapper.updateById(order);
    }

    @Override
    public OrderPageVO myOrderPage(OrderPageRO ro) {
        QueryWrapper<Order> qw = new QueryWrapper<>();
        User currentUser = TokenUtils.getCurrentUser();
        qw.eq("user_id", currentUser.getId());
        Page<Order> orderPage = new Page<>(ro.getCurrent(), ro.getSize());
        IPage<Order> orderIPage = orderMapper.selectPage(orderPage, qw);
        List<OrderPageDTO> orderPageDTOS = Lists.newArrayList();

        orderIPage.getRecords().forEach(order -> {
            OrderPageDTO dto = new OrderPageDTO();
            User user = userService.getById(order.getUserId());
            dto.setApplyUser(user.getUsername());
            dto.setType(order.getAirCondType());
            dto.setReason(order.getSpeculateReason());
            dto.setStatus(order.getStatus().getDesc());
            if (order.getScore() == 0) {
                dto.setScore("-");
            } else {
                dto.setScore(String.valueOf(order.getScore()));
            }
            dto.setId(order.getId());
            if (Objects.nonNull(order.getAppointTime())) {
                dto.setAppointTime(order.getAppointTime());
            }
            if (Objects.nonNull(order.getSubmitTime())) {
                dto.setSubmitTime(order.getSubmitTime());
            }
            User repairer = userService.getById(order.getRepairerId());
            if (Objects.nonNull(repairer)) {
                dto.setRepairer(repairer.getUsername());
            } else {
                dto.setRepairer("-");
            }
            orderPageDTOS.add(dto);
        });
        OrderPageVO vo = new OrderPageVO();
        vo.setRecords(orderPageDTOS);
        vo.setTotal(orderIPage.getTotal());
        vo.setPages(orderIPage.getPages());
        return vo;
    }

    @Override
    public void receive(ReceiveRO ro) {
        Order order = orderMapper.selectById(ro.getId());
        User currentUser = TokenUtils.getCurrentUser();
        assert currentUser != null;
        order.setRepairerId(currentUser.getId());
        order.setStatus(StatusEnum.REPAIR_IN_PROGRESS);
        orderMapper.updateById(order);
        log.info("订单领取成功：{}",order);
        RepairTask task=new RepairTask();
        task.setOrderId(order.getId());
        task.setAppointTime(order.getAppointTime());
        task.setStatus(order.getStatus());
        task.setRepairerId(order.getRepairerId());
        User repairer=userService.getById(order.getRepairerId());
        task.setRepairName(repairer.getUsername());
        task.setAirCondType(order.getAirCondType());
        task.setAirCondCode(order.getAirCondCode());
        task.setSpeculateReason(order.getSpeculateReason());
        task.setRepairReco(order.getRepairReco());
        repairTaskServiceImpl.save(task);
        log.info("维修任务生成成功：{}",task);
    }
}

